//
//  LCNavigationController.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/1.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

class LCNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //  设置代理手势
        self.interactivePopGestureRecognizer?.delegate = self
        
    }
    //自定义一个navigationController，然后重写push操作
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
//        print(viewControllers.count)
       
        //当push的时候隐藏tabbar
        if viewControllers.count > 0 {
            viewController.hidesBottomBarWhenPushed = true
        }
        
         //调用父类的push操作,注意这句代码才是push下一个控制器的关键
        super.pushViewController(viewController, animated: true)
        
        //判断navigation栈中有几个控制器
        if viewControllers.count>1 {
            
            //如果有两个控制器，把第二个控制器的左边barbuttonitem设置成第一个控制器的title
            if viewControllers.count == 2 {
                let title = viewControllers.first?.title
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title!, imageName: "navigationbar_back_withtext",target: self, action: #selector(popAction))
        
            }else{
                //如果超过两个把控制器的左边barbuttonitem都设置成返回
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回",imageName: "navigationbar_back_withtext", target: self, action: #selector(popAction))
            }
            viewController.title = "当前显示的是第\(viewControllers.count)级控制器"
        }
        
    }
    
    //popButton操作
    func popAction(){
        self.popViewController(animated: true)
    }
    
}
//设置手势代理
extension LCNavigationController: UIGestureRecognizerDelegate{
    //是否处理这次点击边缘手势
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        //如果是根视图控制器不开启点击边缘手势
        //因为会有bug，如果根视图控制器也开启点击边缘手势的话,左边会出现黑边
        if viewControllers.count == 1 {
            return false
        }
        
        return true
    }
    
}


